package com.ryandj.config.shiro;

import com.ryandj.exMessage.OOTDException;
import com.ryandj.exMessage.LoginErrMsg;
import com.ryandj.pojo.User;
import com.ryandj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by wdj on 2024/6/3
 */

@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("UserRealm#doGetAuthenticationInfo，执行认证");

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        User user = userService.getUserByLoginName(userToken.getUsername());
        if(user == null){
            log.error("UserRealm#doGetAuthenticationInfo,认证失败，无此用户");
            throw new OOTDException(LoginErrMsg.USER_NOT_FOUND.getCode(), LoginErrMsg.USER_NOT_FOUND.getMessage());
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }
}
